package com.ruoyi.sample.service.impl;

import java.util.*;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.experiment.domain.Circulation;
import com.ruoyi.experiment.domain.Project;
import com.ruoyi.experiment.domain.Sample;
import com.ruoyi.experiment.model.TreeSample;
import com.ruoyi.sample.mapper.SampleLzMapper;
import com.ruoyi.sample.mapper.SampleMapper;
import com.ruoyi.sample.model.SItem;
import com.ruoyi.sample.model.SampleLz;
import com.ruoyi.sample.service.ISampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 样品Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-11
 */
@Service
public class SampleServiceImpl implements ISampleService {
    @Autowired
    private SampleMapper sampleMapper;
    @Autowired
    private SampleLzMapper sampleLzMapper;

    /**
     * 查询样品
     *
     * @param sampleId 样品主键
     * @return 样品
     */
    @Override
    public Sample selectSampleBySampleId(Long sampleId) {
        return sampleMapper.selectSampleBySampleId(sampleId);
    }

    /**
     * 查询样品列表
     *
     * @param sample 样品
     * @return 样品
     */
    @Override
    public List<Sample> selectSampleList(Sample sample) {
        return sampleMapper.selectSampleList(sample);
    }

    @Override
    public List<TreeSample> selectTreeSampleList(Sample sample) {
        List<TreeSample> root = sampleMapper.selectSampleRoot(sample);
        getTree(root);
        return root;
    }

    @Override
    public List<Sample> selectAllSampleBySid(List<Long> ids) {
        return sampleMapper.selectAllSampleBySid(ids);
    }

    private void getTree(List<TreeSample> treeSamples) {
        if (treeSamples == null || treeSamples.isEmpty())
            return;
        for (TreeSample treeSample : treeSamples) {
            List<TreeSample> children = sampleMapper.selectTreeSamples(treeSample.getSampleId());
            treeSample.setChildren(children);
            getTree(children);
        }
    }

    /**
     * 新增样品
     *
     * @param sample 样品
     * @return 结果
     */
    @Override
    public int insertSample(Sample sample) {
        sampleMapper.updateProject(sample.getProjectId());
        Integer c = sampleMapper.checkSampleName(sample.getProjectId(), sample.getSampleName());
        if(c!=0){
            sample.setSampleName(sample.getSampleName()+"("+(c+1)+")");
        }
        int i = sampleMapper.insertSample(sample);
        //记录信息
        SampleLz sampleLz = new SampleLz(sample.getSampleId(), "新增样品", sample.getSampleQuantity(), sample.getSampleSize());
        sampleLzMapper.insertSampleLz(sampleLz);
        return i;
    }

    /**
     * 修改样品
     *
     * @param sample 样品
     * @return 结果
     */
    @Override
    public int updateSample(Sample sample) {
        return sampleMapper.updateSample(sample);
    }

    /**
     * 批量删除样品
     *
     * @param sampleIds 需要删除的样品主键
     * @return 结果
     */
    @Override
    public int deleteSampleBySampleIds(Long[] sampleIds) {
        List<Sample> samples = sampleMapper.selectAllSampleBySid(Arrays.asList(sampleIds));
        int i = sampleMapper.deleteSampleBySampleIds(sampleIds);
        for (Sample sample : samples) {
            sampleMapper.updateSampleStatus(sample.getParentId());
        }
        return i;
    }

    /**
     * 删除样品信息
     *
     * @param sampleId 样品主键
     * @return 结果
     */
    @Override
    public int deleteSampleBySampleId(Long sampleId) {
        return sampleMapper.deleteSampleBySampleId(sampleId);
    }

    @Override
    public List<SItem> selectAllItem(Project project) {
        return sampleMapper.selectAllItem(project);
    }

    @Override
    @Transactional
    public void flume(Circulation circulation) {
        circulation.setUserName(SecurityUtils.getUsername());
        sampleMapper.insertFlume(circulation);
        switch (circulation.getCirculationType()) {
            case 8:
                for (Long id : circulation.getIds()) {
                    confirmLZ(1,id);
                }
                flumeToGLY(circulation.getProjectId(), circulation.getIds());
                break;
            case 9:
                for (Long id : circulation.getIds()) {
                    confirmLZ(1<<2,id);
                }
                changeSample(circulation.getProjectId(), circulation.getIds());
                break;
        }
    }

    @Override
    public boolean flumeBack(List<Long> ids,String person) {
        boolean f = true;
        List<Sample> sampleList = new ArrayList<>();
        for (Long id : ids) {
            Sample sample = sampleMapper.selectSampleBySampleId(id);
            sampleList.add(sample);
            Integer sampleStatus = sample.getSampleStatus();
            if (sampleStatus >= 2) {
                return false;
            }
        }
        for (Sample sample : sampleList) {
            Integer sampleStatus = sample.getSampleStatus();
            if (sampleStatus < 2) {
                sample.setSampleStatus(-1);
                sampleMapper.updateSample(sample);
                sampleLzMapper.insertSampleLz(new SampleLz(sample.getSampleId(),"退回至"+person, sample.getSampleQuantity(), sample.getSampleSize()));
            }
        }
        return f;
    }

    @Override
    public List<Integer> selectSampleStatusBySampleIds(Long[] sampleIds) {
        return sampleMapper.selectSampleStatusBySampleIds(sampleIds);
    }

    @Override
    public List<SampleLz> listLz(SampleLz sampleLz) {
        return sampleLzMapper.selectSampleLzs(sampleLz);
    }

    @Override
    public boolean checkSampleName(Long pid,String name) {
        Integer i = sampleMapper.checkSampleName(pid, name);
        return i==0;
    }

    @Override
    public List<Sample> transformTreeToList(List<TreeSample> tree) {
        List<Sample> res= new ArrayList<>();
        for (TreeSample treeSample : tree) {
            transformTree2List(treeSample,res);
        }
        return res;
    }

    @Override
    public boolean confirmLZ(Integer status, Long id) {
        Sample sample = new Sample();
        sample.setSampleId(id);
        sample.setConfirmStatus(status);
        int i = sampleMapper.updateSample(sample);
        return i==1;
    }

    @Override
    @Transactional
    public int addSamples(List<Sample> samples) {
        StringBuilder names= new StringBuilder();
        for (Sample sample : samples) {
            names.append(sample.getSampleName()).append(",");
            Integer i = sampleMapper.checkSampleName(sample.getProjectId(), sample.getSampleName());
            if (i!=0){
                sample.setSampleName(sample.getSampleName()+"("+(i+1)+")");
            }
            sampleMapper.insertSample(sample);
        }
        sampleMapper.updateProject(samples.get(0).getProjectId());
        //记录信息
        for (Sample sample : samples) {
            SampleLz sampleLz = new SampleLz(sample.getSampleId(), "导入样品:"+sample.getSampleName(),sample.getSampleQuantity(),sample.getSampleSize());
            sampleLzMapper.insertSampleLz(sampleLz);
        }
        return 1;
    }

    private void transformTree2List(TreeSample tree,List<Sample> res){
        if (tree==null)
            return;
        Sample sample = new Sample(tree);
        res.add(sample);
        if (tree.getChildren()==null || tree.getChildren().isEmpty())
            return;
        for (TreeSample child : tree.getChildren()) {
            transformTree2List(child,res);
        }
    }

    private void changeSample(Long pid, List<Long> ids) {
        Sample sample = new Sample();
        sample.setProjectId(pid);
        List<Sample> samples = sampleMapper.selectSampleList(sample);
        Map<Long, Sample> map = new HashMap<>();
        for (Sample s : samples) {
            map.put(s.getSampleId(), s);
        }
        for (Long id : ids) {
            Sample s = map.get(id);
            if (s.getSampleStatus() == null || s.getSampleStatus() < 2) {
                s.setSampleStatus(2);
                sampleMapper.updateSample(s);
                sampleLzMapper.insertSampleLz(new SampleLz(s.getSampleId(),"样品管理员流转至实验管理员",s.getSampleQuantity(),s.getSampleSize()));
            }
        }
    }

    /**
     * 流转样品至项目负责人
     *
     * @param pid
     * @param ids
     */
    private void flumeToGLY(Long pid, List<Long> ids) {
        Sample sample = new Sample();
        sample.setProjectId(pid);
        List<Sample> samples = sampleMapper.selectSampleList(sample);
        Map<Long, Sample> map = new HashMap<>();
        for (Sample s : samples) {
            map.put(s.getSampleId(), s);
        }
        for (Long id : ids) {
            Sample s = map.get(id);
            if (s.getSampleStatus() == null || s.getSampleStatus() < 2) {
                s.setSampleStatus(4);
                sampleMapper.updateSample(s);
                sampleLzMapper.insertSampleLz(new SampleLz(s.getSampleId(),"样品管理员流转至项目负责人",s.getSampleQuantity(),s.getSampleSize()));
            }
        }
    }
}
